package demo1224.lianxi;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo_01 {
   static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {

        List<Student> list = new ArrayList<>();
         read(list);
        while (true) {
            System.out.println("欢迎来到学生管理系统");
            System.out.println("请选择操作：1、添加学生信息\t2、查询学生信息\t3、修改学生信息\t4、删除学生信息\t0退出");
            switch (scan.nextInt()) {
                case 1:
                    add(list);
                    break;
                case 2:
                    findAll(list);
                    break;
                case 3:
//                    modify(list);
                    break;
                case 4:
//                    delete(list);
                    break;
                case 0:
                    System.out.println("退出程序");
                    write(list);
                    return;
                default:
                    System.out.println("输入错误数据");
            }
        }
    }

    private static void findAll(List<Student> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).show();
        }
    }

    private static void add(List<Student> list) {

            System.out.println("请输入学号:");
            String stuId = scan.next();
            for (int i = 0; i < list.size(); i++) {
                Student s1 = list.get(i);
                if (s1.getStuId().equals(stuId)){
                    System.out.println("学号已经存在,添加失败!");
                    return;
                }
            }
            System.out.println("请输入姓名:");
            String name = scan.next();
            System.out.println("请输入性别:");
            String gender = scan.next();
            list.add(new Student(stuId,name,gender));
            System.out.println("添加成功!");

    }

    public static void read(List<Student> list){
        //        把文件中的学生信息读取到集合中
        try {
            BufferedReader br = new BufferedReader(new FileReader("stu.txt"));
            String s ;
            while ((s= br.readLine())!=null){
                String[] arr = s.split(",");
                list.add(new Student(arr[0],arr[1],arr[2]));
            }
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void write(List<Student> list){
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("stu.txt"));
            for (Student s : list) {
                bw.write(s.getStuId()+","+s.getName()+","+s.getGender());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
